<?php
/**
 * 控制登陆后才能访问中间件
 * zhouliang
 * 2020.09.01
 */

namespace App\Http\Middleware;

use App\Exceptions\BasicException;
use App\Http\Controllers\App\Rebuild\PublicApiController;
use App\Repositories\UserRepository;
use Closure;
use App\Services\Tools\JwtService;


class AuthMiddleware {
    /**
     * @param $request
     * @param Closure $next
     * @return mixed
     * @throws BasicException
     */
    public function handle($request, Closure $next) {
        $token = $request->header('Authorization') ?? '';
        $user_id = 0;
        if (env('APP_ENV') != 'production' && is_numeric($token)) {
            $user_id = $token;
        } else {
            $jwtAuth = new JwtService();
            $decoded = $jwtAuth->decode($token);
        }
        if (is_array($decoded) && isset($decoded['data'])) {
            $data = (array)$decoded['data'];
            if (isset($data['uid'])) {
                $user_id = $data['uid'];
            }
        }
        $user = app('model_user')->where('id', $user_id)->first();
        if(!$user){
            throw new BasicException(10008);
        }
        if (!defined('UID')) {
            define('UID', $user_id);
        }


        return $next($request);
    }

    /**用户设备封禁
     * @param $deviceId
     * @throws BasicException
     */
    public function checkUserDevice($deviceId)
    {
        $is_device = app('redis')->sismember('seal:device', $deviceId);
        if ($is_device) {
//            throw new BasicException(10008, "登录设备被封，暂时无法登录");
            app('model_user_seal')->checkSealTime((int)UID, 2, '登录设备被封，暂时无法登录');
        }
    }

    /**用户实名封禁
     * @param $deviceId
     * @throws BasicException
     */
    public function checkUserIDCard($IDCard)
    {
        $is_device = app('redis')->sismember('seal:IDCard', $IDCard);
        if ($is_device) {
//            throw new BasicException(10008, "登录IDCard被封，暂时无法登录");
            app('model_user_seal')->checkSealTime((int)UID, 2, '登录IDCard被封，暂时无法登录');
        }
    }

    /**用户ip封禁
     * @param $deviceId
     * @throws BasicException
     */
    public function checkUserDeviceIp($ip)
    {
        $is_device = app('redis')->sismember('seal:ip', $ip);
        if ($is_device) {
//            throw new BasicException(10008, "登录ip被封，暂时无法登录");
            app('model_user_seal')->checkSealTime((int)UID, 2, '登录ip被封，暂时无法登录');
        }
    }
}
